package com.zzyl.controller.customer;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.zzyl.base.PageResponse;
import com.zzyl.base.ResponseResult;
import com.zzyl.config.RedisService;
import com.zzyl.controller.BaseController;
import com.zzyl.dto.ReservationDTO;
import com.zzyl.service.CustomerReservationService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.ReservationCountVo;
import com.zzyl.vo.ReservationVO;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/customer/reservation")
@Api(tags = "客户预约管理")
public class CustomerReservationController extends BaseController {

    @Autowired
    private CustomerReservationService customerReservationService;

    @Autowired
    private RedisService redisService;

    //查询每个时间段剩余预约次数
    @GetMapping("/countByTime")
    @ApiOperation("查询每个时间段剩余预约次数")
    public ResponseResult<List<ReservationCountVo>> countReservationsForEachTimeWithinTimeRange(
            @ApiParam(value = "时间段", required = true)@RequestParam(required = false) Long time) {
        // 获取当前用户 ID
        Long userId = UserThreadLocal.getUserId();
        // 保存 time 到 Redis
        redisService.saveTime(userId, time);
        List<ReservationCountVo> list = customerReservationService.countReservationsTimeRange(LocalDateTimeUtil.of(time));
        return success(list);
    }

    @GetMapping("/cancelled-count")
    @ApiOperation("查询取消预约数量")
    public ResponseResult<Integer> getCancelledReservationCount() {
        Long userId = UserThreadLocal.getUserId();
        return success(customerReservationService.getCancelledReservationCount(userId));
    }

    //新增预约
    @PostMapping
    @ApiOperation("新增预约")
    public ResponseResult add(@ApiParam(value = "预约信息", required = true)@RequestBody ReservationDTO Reservationdto) {
        customerReservationService.add(Reservationdto);
        return success();
    }


    //分页查询预约
    @GetMapping("/page")
    @ApiOperation("分页查询预约")
    public ResponseResult<PageResponse<ReservationVO>> page(
            @ApiParam(value = "当前页码", required = true)@RequestParam(required = false) Integer pageNum,
            @ApiParam(value = "每页显示条数", required = true)@RequestParam(required = false) Integer pageSize,
            @ApiParam(value = "预约状态", required = true)@RequestParam(required = false) Integer status
    ){
        PageResponse<ReservationVO> pageResponse = customerReservationService.page(pageNum, pageSize, status);
        return success(pageResponse);
    }



    //取消预约
    @PutMapping("/{id}/cancel")
    @ApiOperation("取消预约")
    public ResponseResult cancel(@ApiParam(value = "预约id", required = true)@PathVariable Long id) {
        customerReservationService.cancel(id);
        return success();
    }
}